const Joi = require('joi');
const httpStatus = require('http-status');
const pick = require('../utils/pick');
const ApiError = require('../utils/ApiError');
const logger = require('../config/logger');

/**
 * 请求数据验证中间件
 * @param {Object} schema - Joi验证schema
 * @returns {Function} Express中间件
 */
const validate = (schema) => (req, res, next) => {
  // 调试日志：记录当前路径和完整请求参数
  logger.debug(`[验证] 当前请求路径: ${req.originalUrl}`);
  logger.debug(`[验证] 请求参数: params=${JSON.stringify(req.params)}, query=${JSON.stringify(req.query)}, body=${JSON.stringify(req.body)}`);
  logger.debug(`[验证] 验证schema: ${JSON.stringify(schema)}`);
  
  const validSchema = pick(schema, ['params', 'query', 'body']);
  const object = pick(req, Object.keys(validSchema));
  
  logger.debug(`[验证] 待验证数据: ${JSON.stringify(object)}`);
  
  const { value, error } = Joi.compile(validSchema)
    .prefs({ errors: { label: 'key' }, abortEarly: false })
    .validate(object);

  if (error) {
    const errorMessage = error.details.map((details) => details.message).join(', ');
    logger.error(`[验证] 验证失败: ${errorMessage}`);
    logger.debug(`[验证] 错误详情: ${JSON.stringify(error.details)}`);
    return next(new ApiError(httpStatus.BAD_REQUEST, errorMessage));
  }
  
  logger.debug(`[验证] 验证通过: ${JSON.stringify(value)}`);
  Object.assign(req, value);
  return next();
};

module.exports = validate; 